package com.cjd.view.banner;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;

import androidx.appcompat.widget.LinearLayoutCompat;

import com.cjd.common.R;
import com.cjd.common.utils.DisplayUtil;


public class UnderLineView extends LinearLayoutCompat implements PagerIndicator {

    private int mCurrent = 0;
    private int mTotal = 0;

    private int mSelectedColor = 0xFF377BEE;
    private int mUnSelectedColor = 0xFFC5CEDB;

    public UnderLineView(Context context) {
        super(context);
    }

    public UnderLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setGravity(Gravity.CENTER_HORIZONTAL);

        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.UnderlinePageIndicator, 0, 0);
        if (arr != null) {
            mSelectedColor = arr.getColor(R.styleable.UnderlinePageIndicator_selectedColor, mSelectedColor);
            mUnSelectedColor = arr.getColor(R.styleable.UnderlinePageIndicator_unselectedColor, mUnSelectedColor);
            arr.recycle();
        }
    }

    @Override
    public void setNum(int num) {
        if (num < 0)
            return;

        mTotal = num;
        removeAllViews();
        setOrientation(HORIZONTAL);
        for (int i = 0; i < num; i++) {
            View line = new View(getContext());
            if (i == 0)
                line.setBackgroundColor(mSelectedColor);
            else
                line.setBackgroundColor(mUnSelectedColor);
            LinearLayoutCompat.LayoutParams layoutParams = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1);
            if (i != num - 1)
                layoutParams.setMargins(0, 0, DisplayUtil.INSTANCE.dp2px(6f), 0);
            line.setLayoutParams(layoutParams);
            addView(line);
        }
    }

    @Override
    public int getTotal() {
        return mTotal;
    }

    @Override
    public void setSelected(int index) {
        if (index >= getChildCount() || index < 0 || mCurrent == index) {
            return;
        }
        if (mCurrent < getChildCount() && mCurrent >= 0) {
            getChildAt(mCurrent).setBackgroundColor(mUnSelectedColor);
        }
        getChildAt(index).setBackgroundColor(mSelectedColor);
        mCurrent = index;
    }

    @Override
    public int getCurrentIndex() {
        return mCurrent;
    }


}
